package Service;
import Exceptions.BootstrapException;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ScanXml {
    private static Document getDocument(String path)throws BootstrapException
    {
        SAXReader saxReader = new SAXReader();
        Document res;
        //2.创建DocumentBuilder对象
        try {
            res = saxReader.read(new File(path));
            if(res == null)
            {
                throw new BootstrapException(BootstrapException.ErrorType.FILE_NOTFOUND,"xml文件不存在");
            }
            return res;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static List<BeanDefinition> getAllBeanDefinition(String path)throws BootstrapException
    {
        List<BeanDefinition> res = new ArrayList<>();
        Document doc = getDocument(path);
        Element root = doc.getRootElement();
        List<Element> childrenNode = root.elements("bean");
        if(childrenNode.size() == 0)
        {
            throw new BootstrapException(BootstrapException.ErrorType.PROP_READ_ERROR,"xml文件内容不存在");
        }
        for(Element child: childrenNode){
            BeanDefinition bf = new BeanDefinition(child.attributeValue("id"),child.attributeValue("class"));
            if(bf.id==null || bf.className==null){
                throw new BootstrapException(BootstrapException.ErrorType.FILE_WRITE_ERROR,"xml文件内容有误");
            }


            List<Element> properties = child.elements("properties");
            for (var property: properties){
                //获取name 找不到抛异常
                String name = property.attributeValue("name");
                String value = property.attributeValue("value");
                //如果两中间有空抛出异常
                if(name==null || value==null){
                    throw new BootstrapException(BootstrapException.ErrorType.FILE_WRITE_ERROR,"xml文件内容有误");
                }
                bf.addItem(name,value);
            }
            res.add(bf);
        }
        return res;
    }
}

